package jmind.core.geo;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import jmind.core.support.HttpUtil;

/**
 * 通过google api 得到地理位置信息
 * @author weibo-xie
 * 2012-7-18
 */
public class GeoLocation {
    /**
     * sogou接口
     * http://api.go2map.com/engine/api/regeocoder/json?points=116.33298485714285,39.99676822857143&type=1
     <script type="text/javascript" src="http://www.ip-look-up.com/Services/ipInfo.js"></script> 
    获得经度信息 ipLocation.latitude
    获得维度信息 ipLocation.longitude 
    获得对应的城市 ipLocation.address.city  
    获得相应的国家 ipLocation.address.country  
    国家代码 ipLocation.address.country_code  
    城市所属地区 ipLocation.address.region  
     */
//    public static void main(String[] args) {
//        String lat = "39.99676822857143";
//        String lon = "116.33298485714285";
//        String addr = getAddr(lat, lon);
//        System.out.println(addr);
//
//        getCoordinate("五道口");
//
//    }

    /** 
     * 根据经纬度反向解析地址，有时需要多尝试几次 
     * 注意:(摘自：http://code.google.com/intl/zh-CN/apis/maps/faq.html 
     * 提交的地址解析请求次数是否有限制？) 如果在 24 小时时段内收到来自一个 IP 地址超过 2500 个地址解析请求， 或从一个 IP 
     * 地址提交的地址解析请求速率过快，Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多，则从该 IP 
     * 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。 
     * 
     * @param latitude 
     *            纬度 
     * @param longitude 
     *            经度 
     * @return 
     */
    public static String getAddr(String latitude, String longitude) {
        String addr = "";
        // 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s，不过解析出来的是英文地址 
        // 密钥可以随便写一个key=abc 
        // output=csv,也可以是xml或json，不过使用csv返回的数据最简洁方便解析 
        String url = String.format("http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s", latitude, longitude);
        String data = HttpUtil.get(url);
        if (data != null) {
            String[] retList = data.split(",");
            if (retList.length > 2 && ("200".equals(retList[0]))) {
                addr = retList[2];
                addr = addr.replace("\"", "");
            }
        }
        return addr;
    }

    public static String getCoordinate(String addr) {
        String addrs = "";
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String output = "csv";
        String key = "abc";
        String url = String.format("http://maps.google.com/maps/geo?q=%s&output=%s&key=%s", address, output, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        //进行转码 
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            httpsConn = myURL.openConnection();
            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null) {
                    System.out.println(data);
                    String[] retList = data.split(",");
                    /* 
                             String latitude = retList[2]; 
                             String longitude = retList[3]; 
                             
                             System.out.println("纬度"+ latitude); 
                             System.out.println("经度"+ longitude); 
                             */

                    if (retList.length > 2 && ("200".equals(retList[0]))) {
                        addrs = retList[2];
                        addrs = addr.replace("\"", "");
                    } else {
                        addrs = "";
                    }
                }
                insr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addrs;
    }

    /***
     * 根据经伟度得到详细的地址信息
     * @param x
     * @param y
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String getaddressforxybyGooglehttpconnection(String x, String y) throws IOException {
        if (x.length() > 9) {
            x = x.substring(0, 7);
        }
        if (y.length() > 8) {
            y = y.substring(0, 6);
        }
        URL url = null;
        String mapurl = "http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=" + Float.parseFloat(y) / 100000 + ","
                + Float.parseFloat(x) / 100000;

        String address = "无法从地理信息服务器上获得此位置的地理信息";//取地图的地址

        HttpURLConnection connection = null;
        DataInputStream in = null;
        try {
            url = new URL(mapurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setDefaultUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(1000);
            in = new DataInputStream(connection.getInputStream());
            int all = in.available();
            int code = connection.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                return address;
            } else {
                byte[] b = new byte[all];
                in.read(b);
                String strAddress = new String(b, "UTF-8"); //GBK  2011-04-28
                String[] m_sAddress = strAddress.split(",");
                if (m_sAddress.length == 3) {
                    address = m_sAddress[2];
                } else {
                    address = "无法获取地址";
                }
                //address   =   new   String(b,"UTF-8"); //GBK  2011-04-28
            }
            connection.disconnect();
            in.close();
        } catch (Exception e) {
            address = "无法从地理信息服务器上获得此位置的地理信息";//取地图的地址
        } finally {
            connection.disconnect();
            in.close();
        }
        address = address.replace('"', ' ');
        address = address.replace("<?xml version= 1.0  encoding= GBK ?><R><code>0</code><msg>", "");
        address = address.replace("</msg></R>", "");
        return address;
    }

}
